package com.cat.chapter044;

import java.io.*;

/**
 * @author cat
 * @description
 * @create 2025/7/14 07:56
 * @since JDK17
 */

class Trie01 {
    class Node {
        int pass;
        int end;
        Node[] next = new Node[26];
    }
    Node root;

    public Trie01() {
        root = new Node();
    }

    void insert(String word) {
        Node cur = root;
        cur.pass++;
        for (int i = 0; i < word.length(); i++) {
            int path = word.charAt(i) - 'a';
            if (cur.next[path] == null) {  // 有下一个的位置
                cur.next[path] = new Node();
            }
            cur = cur.next[path];
            cur.pass++;
        }
        cur.end++;
    }

    int search(String word) {
        Node node = find(word);
        return node == null ? 0 : node.end;
    }

    Node find(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            int path = word.charAt(i) - 'a';
            if (cur.next[path] == null) {
                return null;
            }
            cur =  cur.next[path];
        }
        return cur;
    }

    int prefixNumber(String prefix) {
        Node node = find(prefix);
        return node == null ? 0 : node.pass;
    }

    void delete (String word) {
        if (search(word) > 0) {
            Node cur = root, nextNode;
            cur.pass--;
            for (int i = 0; i < word.length(); i++) {
                int path = word.charAt(i) - 'a';
                nextNode = cur.next[path];
                nextNode.pass--;
                if (nextNode.pass == 0) {
                    cur.next[path] = null;
                    return;
                }
                cur = nextNode;
            }
            cur.end--;
        }
    }
}

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
    static StreamTokenizer st = new StreamTokenizer(br);
    public static void main(String[] args) throws IOException {
        Trie01 trie01 = new Trie01();
        st.nextToken();
        int n = ((int) st.nval);
        for (int i = 0; i < n; i++) {
            st.nextToken();
            int opt = ((int) st.nval);
            st.nextToken();
            String word = ((String) st.sval);
            if (opt == 1) {
                trie01.insert(word);
            } else if (opt == 2) {
                trie01.delete(word);
            } else if (opt == 3) {
                pr.println(trie01.find(word) == null ? "NO" : "YES");
            } else {
                pr.println(trie01.prefixNumber(word));
            }
        }
        pr.flush();
        pr.close();
    }
}
